/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author Usuario
 */
public abstract class AbstractDao {
    private Session session;
    private Transaction tx;

    protected void startOperation() throws HibernateException{
        session = HibernateUtil.getSession();
        tx = session.beginTransaction();
    }
    
    protected void handleException(HibernateException he) throws HibernateException {
        tx.rollback();
        //throw new HibernateException("Ocurrió un error en la capa de acceso a datos", he);
        throw he;
    }
    
    protected Session getSession(){
        return session;
    }
    
    protected Transaction getTransaction(){
        return tx;
    }
    
    protected void closeSession(){
        HibernateUtil.closeSession(session);
    }
    
    protected void saveOrUpdate(Object obj) {
        try {
            startOperation();
            session.saveOrUpdate(obj);
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            closeSession();
        }
    }

    protected void persist(Object obj) {
        try {
            startOperation();
            session.persist(obj);
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            closeSession();
        }
    }
    
    protected List findAll(Class clazz, String crit) {
        List objects = null;
        try {
            startOperation();
            Query query = session.createQuery("from " + clazz.getName() + crit);
            objects = query.list();
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            closeSession();
        }
        return objects;
    }
    
    protected void delete(Object obj) {
        try {
            startOperation();
            session.delete(obj);
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            closeSession();
        }
    }
    
    protected Object find(Class clazz, Serializable id) {
        Object obj = null;
        try {
            startOperation();
            obj = session.get(clazz, id);
            tx.commit();
        } catch (HibernateException e) {
            handleException(e);
        } finally {
            closeSession();
        }
        return obj;
    }  
}
